const fs = require('fs');
const COS = require('cos-nodejs-sdk-v5');
const path = require('path');

const cos = new COS({
    SecretId: process.env.COS_KEY,
    SecretKey: process.env.COS_SECRET,
});

const bucketMap = {
    dev: 'yiqiyou-dev-1300033206',
    test: 'yiqiyoo-test-1300033206',
};

const bucket = bucketMap[process.env.PUBLISH_ENV];
const region = 'ap-nanjing';

console.log('bucket:', bucket, bucketMap[process.env.PUBLISH_ENV], process.env.PUBLISH_ENV);

// if (!bucket) return console.error(`env:${process?.NODE_ENV} not found bucket`);

/**上传 */
const uploadDir = (localDir, cosDir) => {
    fs.readdirSync(localDir).forEach(item => {
        const localPath = path.join(localDir, item);
        const cosPath = path.join(cosDir, item);
        if (fs.statSync(localPath).isFile()) {
            // 上传文件
            const fileContent = fs.readFileSync(localPath);
            cos.putObject(
                {
                    Bucket: bucket,
                    Region: region,
                    Key: cosPath,
                    Body: fileContent,
                },
                function (err, data) {
                    console.log(err || '文件上传成功: ' + cosPath);
                }
            );
        } else {
            // 递归处理子目录
            const exists = cosPath.split('/').reduce((promise, folder) => {
                return promise
                    .then(exists => ({
                        exists,
                        cosPath: exists ? cosPath : cosPath + '/',
                    }))
                    .then(({ exists, cosPath }) => {
                        console.log(cosPath);
                        if (!exists) {
                            // 创建目录
                            return cos
                                .putObject({
                                    Bucket: bucket,
                                    Region: region,
                                    Key: cosPath,
                                    Body: '',
                                })
                                .promise()
                                .then(() => cosPath);
                        }
                        return cosPath;
                    });
            }, Promise.resolve(true));

            exists.then(cosPath => {
                uploadDir(localPath, cosPath); // 递归上传子目录
            });
        }
    });
};

/**清理 */
const clearDir = async cosDir => {
    const deleteFiles = async function (marker) {
        const res = await cos.getBucket({
            Bucket: bucket,
            Region: region,
            Prefix: cosDir, // 指定拉取前缀（目录）a
            Marker: marker,
            MaxKeys: 1000,
        });
        const { NextMarker, Contents, IsTruncated } = res;

        const nextMarker = NextMarker;
        const objects = Contents.map(function (item) {
            return { Key: item.Key };
        });

        const deleteMultipleObject = await cos.deleteMultipleObject({
            Bucket: bucket,
            Region: region,
            Objects: objects,
        });
        const { Deleted } = deleteMultipleObject;
        console.log('delete result', Deleted);
        if (IsTruncated === 'true') {
            await deleteFiles(nextMarker);
        } else console.log('delete complete');
    };
    await deleteFiles();
};

const main = async () => {
    // 获取打包输出目录(读取根目录下的buildConfig_web-mobile.json)
    const configFile = path.resolve(__dirname, '../buildConfig_web-mobile.json');

    try {
        // 读取文件内容
        const data = fs.readFileSync(configFile, 'utf8');

        // 解析 JSON 内容
        const config = JSON.parse(data);

        // 获取输出目录
        const localDir = path.join(config.buildPath, config.outputName).replace(/^project:/, '.');

        // web-mobile.json读取
        const GAME_ID = config.name || 'tmp';
        // CI变量配置
        const FEATURE = process.env.FEATURE;

        const cosDir = `social_games/${GAME_ID}/${FEATURE}/client`;
        console.log('环境变量:', process.env.PUBLISH_ENV);
        console.log(`localDir=${localDir}`);
        console.log(`cosDir=${cosDir}`);

        // 清空目录
        await clearDir(cosDir);
        console.log('------------------目录清理完毕------------------');
        // 上传目录
        uploadDir(localDir, cosDir);
        console.log('------------------上传文件完毕------------------');
    } catch (err) {
        console.error('读取文件失败:', err);
    }
};

main();
